<?php

namespace App\Models;


use Illuminate\Database\Eloquent\Model;

class ZPituitaryTags extends Model
{
    protected $table = 'z_pituitary_tags';

    protected $guarded = ['id'];

    /**
     *  获取医院的标签
     * @param $hospId
     * @param $deptId
     * @return array
     */
    public static function getTags($hospId, $deptId)
    {
        return ZPituitaryTags::query()
            ->where([
                'hospital_id' => $hospId,
                'department_id' => $deptId
            ])
            ->orWhere([
                ['hospital_id', 0],
                ['department_id', 0],
                ['is_init', 1]
            ])
            ->where('deleted', 0)
            ->orderBy('is_init', 'desc')
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'desc')
            ->get()->toArray();

    }

    /**
     *  获取医院的标签
     * @param $hospId
     * @param $deptId
     * @param $name
     * @param $hasNum
     * @param $page
     * @param $size
     * @return array
     */
    public static function getHospTagsArr($hospId, $deptId, $name, $hasNum, $page, $size = 10)
    {
        $query = ZPituitaryTags::query()
            ->where([
                'hospital_id' => $hospId,
                'department_id' => $deptId,
                'deleted' => 0
            ])
            ->orWhere([
                ['hospital_id', 0],
                ['department_id', 0],
                ['is_init', 1],
                ['deleted', 0]
            ])
            ->where('deleted', 0)
            ->when($name, function ($query) use ($name) {
                $query->where('name', 'like', '%' . trim($name) . '%');
            });

        $total = $query->count();
        $list = $query
            ->orderBy('is_init', 'desc')
            ->orderBy('sort', 'asc')
            ->orderBy('id', 'desc')
            ->forPage($page, $size)
            ->get()->toArray();

        if ($hasNum) {
            foreach ($list as $k => $item) {
                $list[$k]['used_num'] = self::getUsedNumber($item['id'], $hospId, $deptId);
            }
        }

        $data = [
            'list' => $list,
            'total' => $total
        ];

        return $data;

    }

    /**
     *  获取标签使用人数
     * @param $tagId
     * @param $hospId
     * @param $deptId
     * @return int
     */
    public static function getUsedNumber($tagId, $hospId, $deptId){

        return  ZPituitaryPatientsTag::query()
            ->distinct()
            ->where([
                'hospital_id' => $hospId,
                'department_id' => $deptId
            ])
            ->where('tag_id', $tagId)
            ->count('patient_id');
    }
}